//
//  AppDelegate.m
//  penzer
//
//  Created by caiyc on 2018/9/18.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "AppDelegate.h"
#import "HostHomeViewController.h"
#import <IDLFaceSDK/FaceSDKManager.h>
#import "WXApi.h"
#import "LiveViewController.h"
#import "LoginViewController.h"
#import "HomeViewController.h"
#import "Host_IndexViewController.h"
#import "BIndexViewController.h"
#import <BDCloudAVLicense/BDCloudAVAuthentication.h>
#import <BDCloudMediaPlayer/BDCloudMediaPlayer.h>
#import "WebViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "RZTabBarController.h"
#import "SPNewVersionView.h"

static NSString * const kAccessKey = @"8643cf93d7fa4cf7897b10a7191ca73d";//8643cf93d7fa4cf7897b10a7191ca73d    //36a33862f54f47029ea0a3caedef3b3a
static NSString * const kSecretKey = @"7289921dd22e45139865d9374131c8d1";
static NSString * const kUserId = @"aa53433ed94c41cea1f3bb7168791006";
static NSString *const WeixinAppid = @"wx130fbddb55a30f80";
@interface AppDelegate ()<BDCloudMediaPlayerAuthDelegate,WXApiDelegate,CLLocationManagerDelegate>
{
    CLLocationManager *_locationManager;
}
@end

@implementation AppDelegate
-(void)changeRoot:(NSInteger)type{

    if(type==0){
        HomeViewController *rootVc = [[HomeViewController alloc]init];
        CPNavigation *nav = [[CPNavigation alloc]initWithRootViewController:rootVc];
        [nav setNavigationBarHidden:1];
        self.window.rootViewController = nav;
    }else if(type==1)
    {
        Host_IndexViewController*rootVc = [[Host_IndexViewController alloc]init];
      //  LiveViewController *rootVc = [[LiveViewController alloc]init];
        CPNavigation *nav = [[CPNavigation alloc]initWithRootViewController:rootVc];
        [nav setNavigationBarHidden:1];
        self.window.rootViewController = nav;
    }else{

//        BIndexViewController*rootVc = [[BIndexViewController alloc]init];
//        CPNavigation *nav = [[CPNavigation alloc]initWithRootViewController:rootVc];
//        [nav setNavigationBarHidden:1];
        self.window.rootViewController = [RZTabBarController new];

    }
}


-(void)location{
    _locationManager = [[CLLocationManager alloc] init];
    
    // 设置代理
    
    _locationManager.delegate = self;
    
    // 设置定位精确度到米
    
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    // 设置过滤器为无
    
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    
    // 开始定位
    
    [_locationManager requestAlwaysAuthorization];//这句话ios8以上版本使用。
    
    [_locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:locations[0] completionHandler:^(NSArray *array, NSError *error){
        if(array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            //获取城市
            NSString *city = placemark.locality;
            if(!city) {
                //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
                city = placemark.administrativeArea;
            }
            [XTool SaveDefaultInfo:city Key:LOCATION];
            }
        
        else if(error == nil && [array count] == 0)
            {
            NSLog(@"No results were returned.");
            }
        else if(error != nil)
            {
        NSLog(@"An error occurred = %@", error);
    }
        
    }];
    [manager stopUpdatingLocation];
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 [self load];
[self location];
    
    //审核阶段
//    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
//     NSString *url = @"http://dev.sharepanzer.com/api/bzapi.php?i=10&c=entry&ctrl=live_anchor&ac=store&op=activity&m=bz_activities&token=8175f62516aae4aa5e9ff6fc81b44112&ta=pian";
//    [manager POST:url parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//        SLog(@"请求结果：%@",responseObject);
//        if([responseObject[@"message"][@"data"]integerValue]==1){
//            WebViewController *we = [[WebViewController alloc]init];
//            self.window.rootViewController  = we;
//        }else{
//
//            [self load];
//            [self location];
//        }
//
//    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
//        SLog(@"请求出错===……%@",error);
//    }];
   
    // Override point for customization after application launch.
//    HostHomeViewController *rootVc = [[HostHomeViewController alloc]init];
//    CPNavigation *nav = [[CPNavigation alloc]initWithRootViewController:rootVc];
//    [nav setNavigationBarHidden:1];
//
//    HomeViewController *rootVc = [[HomeViewController alloc]init];
//    CPNavigation *nav = [[CPNavigation alloc]initWithRootViewController:rootVc];
//    [nav setNavigationBarHidden:1];
//
//    self.window.rootViewController = nav;
    
    // 用户认证信息
//    BDCloudAVAuthCredential *credential = [[BDCloudAVAuthCredential alloc] init];
//    credential.userId = kUserId;
//    credential.accessKey = kAccessKey;
//    credential.secretKey = kSecretKey;
    
//    [[BDCloudMediaPlayerAuth sharedInstance] setAccessKey:kAccessKey];
//    // AK/SK方式鉴权
//    // 鉴权成功，error为nil
//    // 鉴权失败，返回相应的error信息
////    [BDCloudAVAuthentication authenticateWithCredential:credential completionHandler:^(NSError *error) {
////        if (error) {
////            NSLog(@"authenticate error, %@",error);
////        }
////    }];
//
    NSString *licensePath = [[NSBundle mainBundle]pathForResource:FACE_LICENSE_NAME ofType:FACE_LICENSE_SUFFIX];
    //NSAssert([], <#desc, ...#>)
    [[FaceSDKManager sharedInstance]setLicenseID:FACE_LICENSE_ID andLocalLicenceFile:licensePath];
    NSLog(@"canwork=%d",[[FaceSDKManager sharedInstance]canWork]);
//    [WXApi registerApp:WeixinAppid];
    
    //新版本升级检测
    [SPNewVersionView check];
    return YES;
}



-(void)load{
    if([XTool GetDefaultInfo:Prole]){
        //有登陆的状态
        NSInteger role = [[XTool GetDefaultInfo:Prole]integerValue];
        [self changeRoot:role];
    }else{
        //没登录任何账号的状态
        LoginViewController *vc = [[LoginViewController alloc]init];
        CPNavigation *nav = [[CPNavigation alloc]initWithRootViewController:vc];
        [nav setNavigationBarHidden:1];
        self.window.rootViewController =nav;
    }
    [[BDCloudMediaPlayerAuth sharedInstance] setAccessKey:kAccessKey];
    // AK/SK方式鉴权
    // 鉴权成功，error为nil
    // 鉴权失败，返回相应的error信息
    //    [BDCloudAVAuthentication authenticateWithCredential:credential completionHandler:^(NSError *error) {
    //        if (error) {
    //            NSLog(@"authenticate error, %@",error);
    //        }
    //    }];
    
    NSString *licensePath = [[NSBundle mainBundle]pathForResource:FACE_LICENSE_NAME ofType:FACE_LICENSE_SUFFIX];
    //NSAssert([], <#desc, ...#>)
    [[FaceSDKManager sharedInstance]setLicenseID:FACE_LICENSE_ID andLocalLicenceFile:licensePath];
    NSLog(@"canwork=%d",[[FaceSDKManager sharedInstance]canWork]);
    [WXApi registerApp:WeixinAppid];
    
}
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    return [WXApi handleOpenURL:url delegate:self];
}
-(void)onResp:(BaseResp*)resp{
    if ([resp isKindOfClass:[PayResp class]]){
        PayResp*response=(PayResp*)resp;
        switch(response.errCode){
            case WXSuccess:
                //服务器端查询支付通知或查询API返回的结果再提示成功
            {
                
                NSDictionary *resultDic = @{@"resultStatus":@"9000"};
                NSDictionary *dic = @{@"payResult":resultDic,@"payType":@"weixin"};
                [[NSNotificationCenter defaultCenter]postNotificationName:@"paynoti" object:nil userInfo:dic];
                
                NSLog(@"支付成功");
            }
                break;
            default:
            {
                NSDictionary *resultDic = @{@"resultStatus":@"6001"};
                NSDictionary *dic = @{@"payResult":resultDic};
                [[NSNotificationCenter defaultCenter]postNotificationName:@"paynoti" object:nil userInfo:dic];
                
                NSLog(@"支付失败，retcode=%d",resp.errCode);
            }
                break;
        }
    }
}

- (void)authStart {
    // 认证开始。
}

- (void)authEnd:(NSError*)error {
    // 认证完成，error为空表示认证成功。
}

- (void)applicationWillResignActive:(UIApplication *)application {
    NSDictionary *dic = @{@"status":@"nocollect"};
      [[NSNotificationCenter defaultCenter]postNotificationName:@"enterback" object:dic];;
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    //进入后台模式
    [[NSNotificationCenter defaultCenter]postNotificationName:@"enterback" object:nil];;
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
     [[NSNotificationCenter defaultCenter]postNotificationName:@"enterback" object:nil];;
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    //重新唤醒
    [[NSNotificationCenter defaultCenter]postNotificationName:@"enterforhead" object:nil];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
